package res

import (
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	"github.com/beego/beego/v2/server/web/context"
	"rate/common/consts"
	"rate/common/i18n"
	"strconv"
)

// 页面响应
type result struct {
	Code int          `json:"code"`
	Msg  string       `json:"message"`
	Data *interface{} `json:"result"`
}

// Success 成功
func Success(c *web.Controller, data interface{}) {
	Result(c, consts.Success, i18n.I(consts.Success, Cl(c.Ctx)), &data)
}

// Created 创建成功
func Created(c *web.Controller, data interface{}) {
	Result(c, consts.SuccessCreated, i18n.I(consts.SuccessCreated, Cl(c.Ctx)), &data)
}

// Fail 失败
func Fail(c *web.Controller, code string) {
	Result(c, code, i18n.I(code, Cl(c.Ctx)), nil)
}

func CtxFail(ctx *context.Context, code string) {
	CtxResult(ctx, code, i18n.I(code, Cl(ctx)), nil)
}

// SystemFail 系统错误
func SystemFail(c *web.Controller) {
	Result(c, consts.SystemError, i18n.I(consts.SystemError, Cl(c.Ctx)), nil)
}

// Cl 获取会员语言
func Cl(ctx *context.Context) string {
	cl := ctx.Input.Header("cl")
	if cl == "" {
		cl = "zh"
	}
	return cl
}

// Result 返回结果context
func Result(c *web.Controller, code string, msg string, data interface{}) {
	// 记录日志
	if code != consts.Success && code != consts.SuccessCreated {
		logs.Error("type=%s, url=%s, data=%, code=%s, msg=%s",
			consts.UserInputErrorType, c.Ctx.Request.RequestURI, string(c.Ctx.Input.RequestBody), code, msg)
	}
	numCode, _ := strconv.Atoi(code)
	c.Data["json"] = result{
		Code: numCode,
		Msg:  msg,
		Data: &data,
	}
	_ = c.ServeJSON()
	c.StopRun()
}

// CtxResult 返回结果context
func CtxResult(c *context.Context, code string, msg string, data interface{}) {
	// 记录日志
	if code != consts.Success && code != consts.SuccessCreated {
		logs.Error("type=%s, url=%s, data=%, code=%s, msg=%s",
			consts.UserInputErrorType, c.Request.RequestURI, string(c.Input.RequestBody), code, msg)
	}
	numCode, _ := strconv.Atoi(code)
	r := result{
		Code: numCode,
		Msg:  msg,
		Data: &data,
	}
	_ = c.Output.JSON(r, true, true)
}
